<script setup lang="ts">
import { useUserStore } from "@/store/user";
import router from "@/router";
import ACCESS_ENUM from "@/access/accessEnum";

const store = useUserStore();
router.beforeEach(async (to, from, next) => {
  let loginUser = store.loginUser;
  //如果之前没有登录，就一直等着用户登录

  if (!loginUser || !loginUser.userRole) {
    await store.getLoginUser();
    loginUser = store.loginUser;
  }

  //to.meta?.access : 当前网页要不要登录验证。
  //ACCESS_ENUM.NOT_LOGIN 默认为不需要
  const webNeedAccess = to.meta?.webAccess ?? ACCESS_ENUM.WEB_NOT_NEED_LOGIN;

  //当前网页需要登录的权限，这个是网页需要
  if (webNeedAccess !== ACCESS_ENUM.WEB_NOT_NEED_LOGIN) {
    //当前用户没有登录
    if (!loginUser || loginUser.userRole === ACCESS_ENUM.USER_NOT_LOGIN) {
      //fullPath : 当前文件的完整路径
      alert("你没有登录，所以访问不了。");
      next(`/user/login/?redirect=${to.fullPath}`);
      return;
    }

    //当前用户登录了，但权限不够

    if (
      webNeedAccess === ACCESS_ENUM.WEB_NEED_ADMIN &&
      loginUser.userRole === ACCESS_ENUM.USER
    ) {
      next("/noauto");
      return;
    }
  }
  //当前用户   登录了 && 权限够
  next();
});
</script>
